<template>
  <div>
    <page-wrapper content-full-height fixed-height>
      <!-- 表格区域 -->
      <vxe-grid id="Mandates" ref="grid" resizable show-overflow highlight-hover-row keep-source row-id="id"
        :columns="tableColumn" :toolbar-config="toolBarConfig" :custom-config="{}" :pager-config="{}"
        :proxy-config="proxyConfig" :loading="loading">
        <!-- 搜索表单 -->
        <template #form>
          <j-border class="search-wrapper">
            <j-form label-width="80px" :model="searchFormData" class="search-form">
              <div class="form-grid">
                <j-form-item label="入库时间" style="width: 100%">
                  <a-range-picker v-model:value="dateRange" :show-time="true" format="YYYY-MM-DD HH:mm:ss"
                    :disabled-date="disabledDate" :disabled-time="disabledRangeTime" @change="handleDateRangeChange" />
                </j-form-item>
                <j-form-item label="供应商" style="width: 100%">
                  <a-select v-model:value="searchFormData.supplierName" allow-clear show-search placeholder="请输入供应商名称"
                    :options="supplierOptions" :field-names="{
                      label: 'name',
                      value: 'name',
                    }" :filter-option="false" @search="handleSupplierSearch"
                    @dropdownVisibleChange="handleSupplierDropdownVisibleChange" />
                </j-form-item>
              </div>
            </j-form>
            <div class="search-btn">
              <a-space>
                <a-button type="primary" :icon="h(SearchOutlined)" @click="search">查询</a-button>
              </a-space>
            </div>
          </j-border>
        </template>

        <!-- 工具栏 -->
        <template #toolbar_buttons>
          <a-space>
            <!-- v-permission="['production:mandates:add']" -->
            <a-button :icon="h(PlusOutlined)" type="primary" @click="$router.push('/production/mandates/add')">
              新增
            </a-button>
            <!-- <a-button v-permission="['production:mandate:add']" :icon="h(PlusOutlined)" type="primary"
              @click="openAddDialog">
              批量新增
            </a-button> -->
            <a-button :icon="h(DeleteOutlined)" @click="handleDelete">删除</a-button>
            <!-- <a-button :icon="h(ReloadOutlined)">重新加工</a-button> -->
            <a-button :icon="h(SettingOutlined)">列设置</a-button>
          </a-space>
        </template>

        <!-- 状态列 -->
        <template #status_default="{ row }">
          <a-tag :color="getStatusColor(row.status)">
            {{ getStatusText(row.status) }}
          </a-tag>
        </template>

        <!-- 操作列 -->
        <template #action_default="{ row }">
          <table-action outside :actions="createActions(row)" />
        </template>
      </vxe-grid>
      <!-- 弹窗组件 -->
      <!-- <add-mandate ref="addDialog" @success="handleSuccess" /> -->
    </page-wrapper>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, h, onMounted } from 'vue';
import {
  SearchOutlined,
  PlusOutlined,
  SettingOutlined,
  CheckOutlined,
  DeleteOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router'; // 添加这行
import { tasksProductionApi } from '/@/api/base-data/product/production-tasks';
import { query } from '/@/api/base-data/supplier';
import { buildSortPageVo } from '/@/utils/utils';

export default defineComponent({
  name: 'ProductionMandate',
  setup() {
    const router = useRouter();
    const loading = ref(false);
    const grid = ref();
    const addDialog = ref();

    const searchFormData = ref({
      mandateCode: '',
      productName: '',
      status: undefined,
      createStartTime: '',
      createEndTime: '',
      supplierName: undefined,
    });

    const tableColumn = [
      { type: 'checkbox', width: 50, fixed: 'left' },
      {
        field: 'action',
        title: '操作',
        width: 160,
        slots: { default: 'action_default' },
        fixed: 'left',
      },
      { field: 'mandateCode', title: '生产单号', width: 140 },
      { field: 'mandateCode', title: '销售单据号', width: 140 },
      { field: 'mandateCode', title: '商品编码', width: 140 },
      { field: 'productName', title: '商品名称', minWidth: 140 },
      { field: 'mandateSKUCode', title: 'SKU编号', width: 140 },
      { field: 'mandateCode', title: '商品品牌', width: 140 },
      { field: 'quantity', title: '订单数量', width: 100 },
      { field: 'quantity', title: '生产数量', width: 100 },
      { field: 'quantity', title: '计划完工日期', width: 140 },
      { field: 'startDate', title: '单据日期', width: 140 },
      { field: 'operator', title: '操作员', width: 140 },
      { field: 'status', title: '状态', width: 100, slots: { default: 'status_default' } },
    ];

    const toolBarConfig = {
      slots: {
        buttons: 'toolbar_buttons',
      },
    };

    // 代理配置
    const proxyConfig = {

      props: {
        result: 'datas',
        total: 'totalCount',
      },
      ajax: {
        query: async ({ page, sorts }) => {
          try {
            // const data = await tasksProductionApi.query(buildQueryParams(page, sorts));
            const data = {
              datas: [
                {
                  id: '001',
                  mandateCode: `MD2023001`,
                  productName: `产品1`,
                  quantity: Math.floor(Math.random() * 100),
                  status: ['PENDING', 'PROCESSING', 'COMPLETED'][2],
                  startDate: '2023-01-01',
                },
                {
                  id: '002',
                  mandateCode: `MD2023002`,
                  productName: `产品2`,
                  quantity: Math.floor(Math.random() * 100),
                  status: ['PENDING', 'PROCESSING', 'COMPLETED'][1],
                  startDate: '2023-01-01',
                },
              ],
              total: 2,
            }
            console.log('Original Data:', data.datas);
            // 对数据进行排序
            data.datas.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
            return data;
          } catch (error) {
            console.error('API Error:', error);
          }
        },
      },
    };
    // 获取数据
    // const loadData = async () => {
    //   try {
    //     loading.value = true;
    //     const res = await getMandateList(searchFormData.value);
    //     tableData.value = res.data;
    //   } catch (error) {
    //     console.error('加载数据失败:', error);
    //     message.error('加载数据失败');
    //   } finally {
    //     loading.value = false;
    //   }
    // };
    const buildSearchFormData = () => {
      return {
        startDate: searchFormData.value.createStartTime,
        endDate: searchFormData.value.createEndTime,
        goodsCode: searchFormData.value.supplierName || ''
      }
    }
    const buildQueryParams = (page, sorts) => {
      return {
        ...buildSortPageVo(page, sorts),
        ...buildSearchFormData(),
      };
    };
    // 状态相关方法
    const getStatusColor = (status: string) => {
      const colorMap: Record<string, string> = {
        PENDING: 'warning',
        PROCESSING: 'processing',
        COMPLETED: 'success',
      };
      return colorMap[status] || 'default';
    };

    /**
     *   未审核：创建成功还未审核
    加工中：已经审核通过，并且目前时间小于计划完工时间
    审核拒绝：审核不通过
    已延期：超过计划完工时间，还未点击"完工"（完工的概率在"加工生产任务"里面）
    已完工：工序点击完工
     */
    const getStatusText = (status: string) => {
      const textMap: Record<string, string> = {
        PENDING: '待处理',
        PROCESSING: '进行中',
        COMPLETED: '审核通过',
      };
      return textMap[status] || '未知';
    };

    // 操作方法
    const search = () => {
      if (grid.value) {
        grid.value.commitProxy('query');
      }
    };

    const openAddDialog = () => {
      addDialog.value?.openDialog();
      // ;
    };

    const handleSuccess = () => {
      search();
    };

    //删除操作
    const handleDelete = async (row) => {
      console.log("===================", row)
      if (!row.datas) {
        message.warning('请选择要删除的生产任务');
        return;
      }
      try {
        await tasksProductionApi.deleteProduct(row);
        message.success('删除成功');
        search();
      } catch (error) {
        message.error('删除失败');
      }
    };

    //操作内容
    const createActions = (row: any) => {
      const actions = [];
      // 查看操作
      actions.push({
        label: '查看',
        onClick: () => {
          router.push({
            path: '/production/mandates/add',
            query: {
              id: row.id,
              mode: 'view'
            },
            meta: {
              title: '查看生产任务'
            }
          });
        }
      });

      // 编辑操作
      if (row.status !== 'COMPLETED') {
        actions.push({
          label: '编辑',
          onClick: () => {
            router.push({
              path: '/production/mandates/add',
              query: {
                id: row.id,
                mode: 'edit'
              },
              meta: {
                title: '编辑生产任务'
              }
            });
          }
        });
      }

      // 只有在非完成状态下才显示删除
      if (row.status !== 'COMPLETED') {
        actions.push({
          label: '删除',
          // permission: 'production:mandate:delete',
          color: 'error',
          popConfirm: {
            title: '确定删除该任务吗？',
            confirm: async () => {
              try {
                // await deleteMandate(row.id);
                message.success('删除成功');
                search();
              } catch (error) {
                message.error('删除失败');
              }
            }
          }
        });
      }

      // 完成状态下显示加工操作
      if (row.status === 'COMPLETED') {
        actions.push({
          label: '加工',
          // permission: 'production:mandate:process',
          onClick: () => {
            router.push(`/production/mandates/process/${row.id}`);
          }
        });
      }

      return actions;
    };

    //点击下拉框，显示供应商列表
    interface QuerySupplierBo {
      id: string;
      name: string;
      // 其他字段根据实际情况补充
    }
    // 添加供应商选项数据
    const supplierOptions = ref<QuerySupplierBo[]>([]);
    // 获取供应商列表
    const loadSuppliers = async (keyword?: string) => {
      try {
        // 构建查询参数
        const params: any = {
          pageSize: 10,
          pageIndex: 1,
          name: keyword,
          sortField: 'createTime',
          sortOrder: 'descend',
        };
        // 只有在有关键字时才添加搜索条件
        if (keyword?.trim()) {
          params.name = keyword.trim();
        }
        const data = await query(params).then(res => res);
        // console.log('Supplier Data:', data);
        // 这里需要替换成实际的 API 调用
        supplierOptions.value = data.datas || [];
      } catch (error) {
        console.error('获取供应商列表失败:', error);
        // message.error('获取供应商列表失败');
      }
    };

    // 修改搜索处理方法
    const handleSupplierSearch = async (value: string) => {
      // 无论是否有搜索值都调用加载方法
      await loadSuppliers(value);
    };

    // 修改下拉框打开事件处理
    const handleSupplierDropdownVisibleChange = (open: boolean) => {
      if (open) {
        // 打开时加载最近的10个供应商（不带搜索关键字）
        loadSuppliers();
      }
    };

    // 添加日期范围数据
    const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>();
    // 禁用日期
    const disabledDate = (current: dayjs.Dayjs) => {
      // 不能选择未来的日期
      return current && current > dayjs().endOf('day');
    };

    // 禁用时间
    const disabledRangeTime = (
      _: dayjs.Dayjs | null,
      type: 'start' | 'end'
    ) => {
      if (type === 'end') {
        const now = dayjs();
        if (dateRange.value?.[1]?.isSame(now, 'day')) {
          return {
            disabledHours: () => getDisabledHours(now.hour()),
            disabledMinutes: (hour: number) => getDisabledMinutes(now.hour(), hour, now.minute()),
            disabledSeconds: (hour: number, minute: number) =>
              getDisabledSeconds(now.hour(), hour, now.minute(), minute, now.second()),
          };
        }
      }
      return {};
    };

    // 获取禁用的小时
    const getDisabledHours = (currentHour: number) => {
      const hours = [];
      for (let i = currentHour + 1; i < 24; i++) {
        hours.push(i);
      }
      return hours;
    };

    // 获取禁用的分钟
    const getDisabledMinutes = (currentHour: number, selectedHour: number, currentMinute: number) => {
      if (selectedHour === currentHour) {
        const minutes = [];
        for (let i = currentMinute + 1; i < 60; i++) {
          minutes.push(i);
        }
        return minutes;
      }
      return [];
    };
    // 获取禁用的秒数
    const getDisabledSeconds = (
      currentHour: number,
      selectedHour: number,
      currentMinute: number,
      selectedMinute: number,
      currentSecond: number
    ) => {
      if (selectedHour === currentHour && selectedMinute === currentMinute) {
        const seconds = [];
        for (let i = currentSecond + 1; i < 60; i++) {
          seconds.push(i);
        }
        return seconds;
      }
      return [];
    };

    // 处理日期变化
    const handleDateRangeChange = (dates: [dayjs.Dayjs, dayjs.Dayjs] | null) => {
      if (dates) {
        searchFormData.value.createStartTime = dates[0]?.format('YYYY-MM-DD HH:mm:ss');
        searchFormData.value.createEndTime = dates[1]?.format('YYYY-MM-DD HH:mm:ss');
      } else {
        searchFormData.value.createStartTime = '';
        searchFormData.value.createEndTime = '';
      }
    };

    onMounted(() => {
      loadSuppliers();
      // loadData();
    });

    return {
      h,
      loading,
      grid,
      addDialog,
      searchFormData,
      SearchOutlined,
      tableColumn,
      toolBarConfig,
      search,
      openAddDialog,
      PlusOutlined,
      DeleteOutlined,
      CheckOutlined,
      SettingOutlined,
      ReloadOutlined,
      handleSuccess,
      createActions,
      getStatusColor,
      getStatusText,
      proxyConfig,
      supplierOptions,
      handleSupplierSearch,
      handleSupplierDropdownVisibleChange,
      dateRange,
      disabledDate,
      disabledRangeTime,
      handleDateRangeChange,
      handleDelete,
    };
  },
});
</script>

<style lang="less" scoped>
.search-wrapper {
  position: relative;
  background-color: #fff;
  padding: 16px;
  border-radius: 2px;

  :deep(.search-form) {
    width: 60%;
    margin-right: 100px;

    .form-grid {
      display: grid;
      grid-template-columns: repeat(1, 1fr);
      gap: 20px;
    }

    .ant-form-item {
      margin: 0;
    }

    .ant-input,
    .ant-select {
      width: 100%;
    }
  }

  .search-btn {
    position: absolute;
    right: 16px;
    bottom: 16px;
  }
}

.table-wrapper {
  background-color: #fff;
  padding: 16px;
  border-radius: 2px;
  height: calc(100vh - 180px);
}
</style>
